<?php

class userModel
{

    /**
     * 基类
     * @var object
     */
    private $base;

    /**
     * Mysql 连接
     * @var resources
     */
    private $db;

    /**
     * Redis 连接
     * @var resources
     */
    private $redis;

    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /**
     * 退出登陆
     * @param type $uid
     * @param type $nickname
     * @return boolean
     */
    public function logout($uid)
    {
        /* 记录日志*/
        $logInfo = '['.date('Y-m-d H:i:s')."]\tuid:[".$uid."]\tclient:[".$this->base->client."]\n";

        $this->base->load('log')->writeLog('logout', $logInfo,'logout.txt');

        return 1;
    }
    /**
     * 获取用户隐私设置
     * @return array()
     */
    public function getPrivacy($uid)
    {
        $default = array('gender'=>1,'age'=>1,'constellation'=>1,'occupation'=>1,'location'=>1);
        $result = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'privacy');
        $result = @json_decode($result, true);

        empty($result) && $result = array();
        $result = array_merge($default, $result);
        return $result;
    }
    /**
     * 设置隐私
     * @return array()
     */
    public function setPrivacy($uid, $privacy)
    {
        $prePrivacy = $this->getPrivacy($uid);
        $privacy = array_merge($prePrivacy, $privacy);
        $privacy = json_encode($privacy);
        if($this->db->update("update r_user set privacy = '{$privacy}' where uid = '{$uid}'"))
        {
            $this->redis->hset(REDIS_PREFIX.'UserInfo_'.$uid, 'privacy', $privacy);
        }
        return $this->getPrivacy($uid);
    }
    /**
     * 生成用户名
     * @return array()
     */
    public function makeNickname($name = '')
    {
        $repeat = true;
        do {
            $nickname = $name ? $name.common::getHashStr(3) : $this->base->config['USER_PRE'].common::getHashStr(9);
            $repeat = $this->db->getOne("select uid from r_user where nickname = '{$nickname}' limit 1") != false;
        } while ($repeat === true);
        return $nickname;
    }

    /**
     * 获取im_token为空的所有用户
     * 
     * @return [type] [description]
     */
    public function getUserInfoByIMTokenIsNull(){
        return $this->db->getAll("select * from r_user where im_token = '' limit 1000");
    }
    
    /**
     * 获取用户
     */
    public function getUserInfo($uid){
        return $this->db->getRowTable('r_user',array(),"uid = '{$uid}'");
    }

    /**
     * 更新用户的im_token的值
     * @return [type] [description]
     */
    public function updateUserInfo($uid,$im_token){
        $sql = "update r_user set im_token = '" . $im_token . "' where uid = '" . $uid . "'";
        return $this->db->update($sql);
    }
    /**
     * 搜索用户
     * @param  $nickname 用户昵称
     * @param  $p 分页页码
     * @param  $offset 数量
     * @return   array()
     */
    public function searchUsers($nickname, $p=1, $offset = 20)
    {
        $nickname = trim($nickname);
        $p = intval($p);
        $p <= 0 && $p = 1;
        if($p * $offset > 100)
        {
            $result = array();
        }
        else
        {
            $start = ($p - 1) * $offset;

            $res = $this->base->load('xunSearch')->init('user')->search("$nickname",'uid',$offset,$p);
            if(empty($res)){
                return array();
            }
            $result = [];
            foreach($res as $v){
                $result[] = $this->getUserInfo($v->uid);
            }
            
            //$result = $this->db->getAll("select uid, nickname, header, gender, province, city, total_mileage, total_rate from r_user where nickname like '%{$nickname}%' order by uid DESC limit $start, $offset");
            !$result && $result = array();
        }
        
        return $result;
    }
    /**
     * 检测用户昵称是否可以使用
     * @param string $nickname
     * @return int
     */
    public function checkNickname($nickname, $uid = 0)
    {
        $result = -1;

        $len = mb_strlen($nickname, 'utf-8');

        // 判断昵称长度与格式是与合法
        if ($len >= 1 && $len <= 20 && preg_match('/^[A-Za-z0-9\x80-\xff\s\']+$/', $nickname))
        {
            // 判断昵称是否存在违禁词
            if (!$this->base->load('badwords')->check($nickname))
            {
                // 判断昵称是否已被使用
                $checkSql = "select count(uid) from r_user where nickname='{$nickname}'";
                !empty($uid) && $checkSql .= " and uid != '{$uid}'";
                if (!$this->db->getOne($checkSql))
                {
                    $result = 1;
                } else
                {
                    $result = -3;
                }
            } else
            {
                $result = -2;
            }
        }

        return $result;
    }


    public function setMessagePushSetting($uid, $group_receive){
        
        $group_receive = json_decode($group_receive,true);
        $this->db->delDataTable('r_user_message_push_setting', " uid = '{$uid}' ");
        foreach ($group_receive as $key => $item) {
            $gid = $item['gid'];
            $is_open = $item['is_open'];
            $insertArr = array('uid' => $uid,'gid' => $gid,'is_open' => $is_open,'time' => time());
            $rst = $this->db->insertRowTable('r_user_message_push_setting', $insertArr);
            // $rst = $this->db->getRow("select id from r_user_message_push_setting where uid = '$uid' and gid = '$gid'");
            // if($rst){
            //     $insertArr['id'] = $rst['id'];
            //     $rst = $this->db->updateRowTable('r_user_message_push_setting', $insertArr);
            // }else{
            //     $rst = $this->db->insertRowTable('r_user_message_push_setting', $insertArr);
            //}
        }
        return true;
    }

    public function getMessagePushSetting($uid){
        return $this->db->getAll("select gid,is_open from r_user_message_push_setting where uid = '{$uid}'");
    }

    /**
     * 获取用户打卡次数
     * @param int $uid
     * @return array 
     */
    public function getAttendance($uid)
    {
        $attendance = 0;

        if(!$uid)
        {
            return $attendance;
        }

        return $attendance;

        $attendance = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$uid, 'attendance');

        if($attendance === false)
        {
            // $attendance = 
        }
    }
    /**
     * 保存用户坐标
     * @param int uid 用户id
     * @param float lat  纬度
     * @param float lng  经度
     * @return array 
     */
    public function setCoordinate($uid, $lat, $lng)
    {
        if($uid)
        {
            $coordinate = compact('uid', 'lat', 'lng');

            $this->db->updateRowTable('r_user', $coordinate);
        }
        return;
    }

    /**
     * 通过手机号获取用户信息
     * @param $phone
     * @return bool
     */
    public function getInfoByPhone($phone){
        if(empty($phone))
            return false;
        return $this->db->getRowTable('r_user',array(),"phone='{$phone}'");
    }


    //========================通讯录相关========================
    /**
     * 通过cid获取通讯录
     * @param $cid
     * @param $phone
     * @param string $uids
     * @param int $status
     * @param $page
     * @param int $row
     * @return mixed
     */
    public function getPhonesByCid($cid,$phone,$uids='',$status=1,$page,$row=15){
        $offset = ($page-1) * $row;
        if($status==1){
            $where_ext = "";
            if(!empty($uids)){
                $uids = implode(',',$uids);
                $where_ext .= " AND u.uid not in($uids)";
            }
            $info = $this->db->getAll("select a.name,u.uid,u.nickname,u.total_mileage,u.header from r_address_book a left join r_user u on a.phone=u.phone where clientid='$cid' and status=$status and a.phone != '$phone' $where_ext limit $offset,$row");
        }else{
            $info = $this->db->getAll("select phone,name from r_address_book where clientid='$cid' and status=$status limit $offset,$row");
        }
        return $info;
    }

    /**
     * 通过cid,phone获取信息
     * @param $cid
     * @param $phone
     * @return mixed
     */
    public function getInfo($cid,$phone){
        return $this->db->getRow("select phone from r_address_book where clientid='$cid' and phone='$phone'");
    }

    /**
     * 修改通讯录状态
     * @param $phone
     * @param $status
     * @return mixed
     */
    public function updateStatus($phone,$status){
        $sql = "update r_address_book set status=$status where phone='$phone'";
        return $this->db->update($sql);
    }

    /**
     * 获取马甲号
     * @param int $page
     * @param int $row
     * @return mixed
     */
    public function getRobot($page=1,$row=20){
        $offset = ($page-1)*$row;
        $sql = "select * from r_user where is_robot=1 order by uid desc limit $offset,$row";
        $data = $this->db->getAll($sql);
        return $data;
    }

    public function insert($data){
        $uid = $this->db->insertRowTable('r_user', $data);
        if($data['nickname'] && $uid){
            $this->base->load('xunSearch')->init('user')
                ->addIndex(['uid'=>$uid,'nickname'=>$data['nickname']]);
        }
        return $uid;
    }

    public function update($data){
        if(!isset($data['uid'])){
            return false;
        }
        $userData = ['uid' => $data['uid']];
        isset($data['nickname']) && $userData['nickname'] = $data['nickname'];
        isset($data['header']) && $userData['header'] = $data['header'];
        isset($data['header_source']) && $userData['header_source'] = $data['header_source'];
        isset($data['height']) && $userData['height'] = $data['height'];
        isset($data['weight']) && $userData['weight'] = $data['weight'];
        isset($data['gender']) && $userData['gender'] = $data['gender'];
        isset($data['age']) && $userData['age'] = $data['age'];
        isset($data['total_mileage']) && $userData['total_mileage'] = $data['total_mileage'];
        isset($data['total_elapsedtime']) && $userData['total_elapsedtime'] = $data['total_elapsedtime'];
        isset($data['total_calorie']) && $userData['total_calorie'] = $data['total_calorie'];
        isset($data['total_rate']) && $userData['total_rate'] = $data['total_rate'];
        isset($data['max_mileage']) && $userData['max_mileage'] = $data['max_mileage'];
        isset($data['max_elapsedtime']) && $userData['max_elapsedtime'] = $data['max_elapsedtime'];
        isset($data['max_speed']) && $userData['max_speed'] = $data['max_speed'];
        isset($data['max_five_time']) && $userData['max_five_time'] = $data['max_five_time'];
        isset($data['max_ten_time']) && $userData['max_ten_time'] = $data['max_ten_time'];
        isset($data['max_half_mtime']) && $userData['max_half_mtime'] = $data['max_half_mtime'];
        isset($data['max_mara_time']) && $userData['max_mara_time'] = $data['max_mara_time'];
        isset($data['rank']) && $userData['rank'] = $data['rank'];
        isset($data['addtime']) && $userData['addtime'] = $data['addtime'];
        isset($data['birthday']) && $userData['birthday'] = $data['birthday'];
        isset($data['level']) && $userData['level'] = $data['level'];
        isset($data['total_energy']) && $userData['total_energy'] = $data['total_energy'];
        isset($data['lights']) && $userData['lights'] = $data['lights'];
        isset($data['occupation']) && $userData['occupation'] = $data['occupation'];
        isset($data['occupa_type']) && $userData['occupa_type'] = $data['occupa_type'];
        isset($data['province']) && $userData['province'] = $data['province'];
        isset($data['city']) && $userData['city'] = $data['city'];
        isset($data['signature']) && $userData['signature'] = $data['signature'];
        isset($data['background']) && $userData['background'] = $data['background'];
        isset($data['constellation']) && $userData['constellation'] = $data['constellation'];
        isset($data['cid']) && $userData['cid'] = $data['cid'];
        isset($data['lastcid']) && $userData['lastcid'] = $data['lastcid'];
        isset($data['sid']) && $userData['sid'] = $data['sid'];
        isset($data['key']) && $userData['key'] = $data['key'];
        isset($data['qq']) && $userData['qq'] = $data['qq'];
        isset($data['sina']) && $userData['sina'] = $data['sina'];
        isset($data['weixin']) && $userData['weixin'] = $data['weixin'];
        isset($data['renren']) && $userData['renren'] = $data['renren'];
        isset($data['fromChannel']) && $userData['fromChannel'] = $data['fromChannel'];
        isset($data['privacy']) && $userData['privacy'] = $data['privacy'];
        isset($data['im_token']) && $userData['im_token'] = $data['im_token'];
        isset($data['lat']) && $userData['lat'] = $data['lat'];
        isset($data['lng']) && $userData['lng'] = $data['lng'];
        isset($data['phone']) && $userData['phone'] = $data['phone'];
        isset($data['pwd']) && $userData['pwd'] = $data['pwd'];
        isset($data['is_robot']) && $userData['is_robot'] = $data['is_robot'];
        isset($data['is_defaultData']) && $userData['is_defaultData'] = $data['is_defaultData'];
        isset($data['target_weight']) && $userData['target_weight'] = $data['target_weight'];
        isset($data['best_record']) && $userData['best_record'] = $data['best_record'];
        
        $res = $this->db->updateRowTable('r_user',$userData);
        $fields = ['uid','nickname'];
        $row = array_intersect_key($userData,array_flip($fields));
        if(count($row) == 2 && $res){
            $this->base->load('xunSearch')->init('user')->updateIndex($row);
        }
        return $res;
    }

    /**
     * @return int 检测用户是否被禁止聊天 0:否 1：是
     */
    public function checkChatIsForbid(){
        $forbidFunc = $this->getForbidFunction();
        $forbidChat = 0;
        if(!empty($forbidFunc) && in_array('chat',$forbidFunc)){
            $forbidChat = 1;
        }
        return $forbidChat;
    }

    /**
     * 获取某个用户/设备禁掉的功能
     * @return array
     */
    public function getForbidFunction(){
        $forbidFunc = $this->redis->get(REDIS_PREFIX."BlackUser_".$this->base->uid);
        !$forbidFunc && $forbidFunc = $this->redis->get(REDIS_PREFIX."BlackUser_".$this->base->client);
        return $forbidFunc ? json_decode($forbidFunc,true) : array();
    }

    /*
     * 通过nickname获得uid
     */
    public function getUidByNickname($nickname){
        $sql = "select uid from r_user where nickname='$nickname' limit 1";
        return $this->db->getOne($sql);
    }

    /**
     *  按日期记录用户体重数据
     * @param $uid
     * @param $weight  单位（Kg）
     * @return mixed
     */
    public function addUserWeightData($uid, $weight)
    {
        $insertData = ['uid'=>$uid,'weight'=>$weight,'date'=>date('Ymd')];
        return $this->db->insertRow('r_data_day', $insertData, mysqldb::INSERT_ON_UPDATE);
    }

    /**
     * 同步更新用户信息中的体重
     * @param $uid
     * @param $weight  单位（Kg）
     * @return mixed
     */
    public function updateUserWeight($uid, $weight)
    {
        $result = $this->db->update("UPDATE r_user SET weight=$weight WHERE uid = $uid");
        if ($result) {//更新缓存值
            $this->redis->hSet(REDIS_PREFIX . 'UserInfo_' . $uid, 'weight', $weight);
        }
        return  $result;
    }

    /**
     *  同步更新记录表：每天用户体重的数据
     */
    public function updateUserWeightForDay($uid, $weight,$statDay)
    {
        $result = $this->db->update("UPDATE r_data_day SET weight=$weight WHERE uid = $uid AND date='$statDay'");
        //缓存优化 后期有时间加上 todo
        return  $result;
    }


    /**
     * 查询七天按天分组的用户体重数据
     * @param $uid
     * @param $endTime
     * @return array
     */
    public function getWeightDataForChart($uid, $endTime)
    {
        //缓存优化 后期有时间加上 todo
        $startTime = date('Ymd', strtotime('-6 days',strtotime($endTime)));
        $sql = "select date,weight,calorie from r_data_day
                where uid=$uid
                and date >=$startTime
                and date <=$endTime
                ORDER BY date asc";
        $list  = $this->db->getAll("$sql");
        $result = [];
        if ($list) {
            foreach ($list as $key=>$val) {
                $result[$val['date']] = array(
                    'formatTime'=>date('Ymd', strtotime($val['date'])),
                    'weight'    =>(double)$val['weight'],
                    'calorie'   =>(int)$val['calorie']
                );
            }
        }
        /*补全用户没跑的时间，用于APP Char展示*/
        $intStartTime = strtotime($startTime);
        $intEndTime = strtotime($endTime);
        for($i=$intStartTime; $i<=$intEndTime; $i=$i+86400){
            if (!array_key_exists(date('Ymd',$i), $result)) {
                $result[date('Ymd',$i)] =  array(
                    'formatTime'=>date('Ymd',$i),
                    'weight'    =>0,
                    'calorie'   =>0
                );
            }
            ksort($result);//键名重新排序，保证输出的日期排序从小到大
        }
        return array_values($result);
    }
    
    /*
     * 获得未读徽章
     */
    public function getCertificateCount($uid){
        $num = $this->redis->hget(REDIS_PREFIX . 'UserInfo_'.$uid, 'certificate_count');
        !$num && $num = 0;
        return $num;
    }
    
    /*
     * 设置未读徽章
     */
    public function setCertificateCount($uid,$new_num){
        if(is_numeric($new_num)){
            $new_num < 0 && $new_num = 0;
            $this->redis->hset(REDIS_PREFIX . 'UserInfo_'.$uid, 'certificate_count',$new_num);
        }
    }
    
    /*
     * 设置新徽章提醒
     */
    public function setCertificateNotify($uid,$notify=1){
        $this->redis->hset(REDIS_PREFIX . 'UserInfo_'.$uid, 'certificate_notify',$notify ? 1 : 0);
    }
    
    /*
     * 设置个人额外信息
     */
    public function setUserExt($uid,array $_row){
        $row = $_row;
        $row['uid'] = $uid;
        $this->db->updateRowTable('r_user_ext',$row);
        $this->redis->hmset(REDIS_PREFIX . 'UserInfo_'.$uid, $row);
    }

    /**
     * 获取用户的微信公众号OpenID
     */
    public function getWxPubOpenId()
    { 
        return !empty($_COOKIE['wxpo']) ? $_COOKIE['wxpo'] : NULL;
    }

    /**
     * 检测用户的微信公众号OpenID
     */
    public function checkWxPubOpenId()
    {
        if(!$this->getWxPubOpenId())
        {
            $wx = $this->base->loadlib('wx');
            $wxUrl = $wx->pubOpenIdUrl();

            $rurl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            setcookie('rurl', $rurl, time() + 864000, '/', '.hupu.com', FALSE, TRUE);
            setcookie('rurl', $rurl, time() + 864000, '/', '.ijoggers.com', FALSE, TRUE);

            common::go($wxUrl);
        }
    }
    
    /*
     * 用户是否有小号权限
     */
    public function canChangeFace($uid){
        return $this->db->getOne("select id from r_usertag where tagId=1 and uid='$uid' limit 1") ? 1 : 0;
    }
}
